package com.dkd.manage.service.Impl;

import com.dkd.manage.exception.DeleteException;
import com.dkd.manage.mapper.NodeMapper;
import com.dkd.manage.mapper.RegionMapper;
import com.dkd.manage.pojo.dto.NodeQueryListDto;
import com.dkd.manage.pojo.dto.RegionQueryListDto;
import com.dkd.manage.pojo.entity.Region;
import com.dkd.manage.pojo.vo.NodeVo;
import com.dkd.manage.pojo.vo.RegionVo;
import com.dkd.manage.result.PageResult;
import com.dkd.manage.service.RegionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class RegionServiceImpl implements RegionService {


    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private NodeMapper nodeMapper;


    /**
     * 分页查询区域列表
     * @param regionQueryListDto
     * @return
     */
    @Override
    public PageResult<RegionVo> list(RegionQueryListDto regionQueryListDto) {
        //开启分页
        PageHelper.startPage(regionQueryListDto.getPageNum(), regionQueryListDto.getPageSize());
        //查询区域列表
        List<RegionVo> regionList = regionMapper.list(regionQueryListDto);
        //创建分页详情对象
        PageInfo<RegionVo> pageInfo = new PageInfo<>(regionList);
        //封装数据返回
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 新增区域
     * @param region
     */
    @Override
    public Integer add(Region region) {
        return regionMapper.add(region);
    }

    /**
     * 修改区域
     * @param region
     * @return
     */
    @Override
    public Integer edit(Region region) {
        return regionMapper.edit(region);
    }

    /**
     * 根据id查询区域
     * @param id
     * @return
     */
    @Override
    public Region getRegionById(Long id) {
        return regionMapper.getRegionById(id);
    }

    /**
     * deleteRegionById
     * @param ids
     * @return
     */
    @Override
    public Integer deleteRegionById(Long[] ids) {
        NodeQueryListDto nodeQueryListDto = NodeQueryListDto.builder()
                .pageNum(1)
                .pageSize(10)
                .build();
        //根据区域Id查询点位
        for (Long id : ids) {
            nodeQueryListDto.setRegionId(id);
            List<NodeVo> nodeVoList = nodeMapper.list(nodeQueryListDto);
            if(nodeVoList != null && nodeVoList.size() > 0) {
                throw new DeleteException("要删除的区域下关联了点位数据，无法删除");
            }
        }
        return regionMapper.deleteRegionById(ids);
    }
}
